package fw_bak

import (
	"fmt"
	"log"
	"mysql_bak/fw_config"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"syscall"
	"time"
)

var logger *log.Logger

func Init() {
	_ = os.MkdirAll(fw_config.GetConfigHandler().GetString("backupDir"), 0755)
	logFile, err := os.OpenFile(filepath.Join(fw_config.GetConfigHandler().GetString("backupDir"), "backup_log.txt"),
		os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		log.Fatalf("打开日志文件失败: %v", err)
	}
	logger = log.New(logFile, "", 0)
}

// 真正备份逻辑（与之前相同）
func Backup() {
	ts := time.Now().Format("20060102_150405")
	sqlFile := filepath.Join(fw_config.GetConfigHandler().GetString("backupDir"), fmt.Sprintf("full_backup_%s.sql", ts))

	args := []string{
		fmt.Sprintf("--user=%s", fw_config.GetConfigHandler().GetString("mysqlUser")),
		fmt.Sprintf("--password=%s", fw_config.GetConfigHandler().GetString("mysqlPassword")),
		"--databases", fw_config.GetConfigHandler().GetString("database"),
		"--single-transaction",
		"--quick",
		"--add-drop-database",
		"--default-character-set=utf8mb4",
		"--result-file=" + sqlFile,
	}

	cmd := exec.Command(fw_config.GetConfigHandler().GetString("mysqldumpPath"), args...)
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} // 关键一行
	cmd.Stderr = logger.Writer()
	if err := cmd.Run(); err != nil {
		logger.Printf("[%s] 备份失败: %v\n", time.Now().Format("2006-01-02 15:04:05"), err)
		return
	}
	logger.Printf("[%s] 备份成功！文件路径：%s\n", time.Now().Format("2006-01-02 15:04:05"), sqlFile)
	// 清理旧文件
	cutoff := time.Now().AddDate(0, 0, -fw_config.GetConfigHandler().GetInt("keepDays"))
	_ = filepath.Walk(fw_config.GetConfigHandler().GetString("backupDir"), func(path string, info os.FileInfo, err error) error {
		if err != nil || info.IsDir() {
			return nil
		}
		if strings.HasPrefix(info.Name(), "full_backup_") && strings.HasSuffix(info.Name(), ".sql") {
			if info.ModTime().Before(cutoff) {
				_ = os.Remove(path)
				logger.Printf("删除旧文件: %s\n", path)
			}
		}
		return nil
	})
}
